package operation;

import book.Book;
import book.BookList;

import java.util.Scanner;

public class DelOperation implements IOperation {
    @Override
    public void work(BookList bookList) {
        System.out.println("删除图书");
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要删除的图书名: ");
        String name = scanner.nextLine();

        int currentSize = bookList.getUsedSize();
        int i = 0;
        int index = -1;
        for(;i < currentSize;i++) {
            Book tmp = bookList.getBook(i);//获取到书
            if(tmp.getName().equals(name)) {//判断该书是否存在,存在,记录下标
                index = i;
                break;
            }
        }

        //遍历完返回
        if(i >= currentSize) {
            System.out.println("不存在您需要删除的图书");
            return;
        }

        //break返回,后一个覆盖前一个
        for(int j = index;j < currentSize - 1;j++) {
            //后一本书覆盖前一本书
            Book book = bookList.getBook(j + 1);//获取进行覆盖的书
            //进行覆盖
            bookList.setBook(book,j);//j下标被覆盖为j+1下标
        }

        //回收最后一个位置的引用
        bookList.setBook(null,currentSize-1);
        //删除后,书数-1
        bookList.setUsedSize(currentSize-1);

        System.out.println("删除成功!");
    }
}
